package tk3;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.umundo.core.Message;
import org.umundo.core.Node;
import org.umundo.core.Publisher;
import org.umundo.core.Receiver;
import org.umundo.core.Subscriber;

public class TK3Chat {
	
	static {	
		System.loadLibrary("umundocoreSwig");
	}
	
	private Publisher pub;
	private Subscriber sub;
	private Node node;
	
	TK3Chat() {
	}
	
	public void goOnline() {
		node = new Node("tk3");
		pub = new Publisher("chat");
		sub = new Subscriber("chat", new Receiver() {
			@Override
			public void receive(Message msg) {
				System.out.println("received an unknown message. Payload " + new String(msg.getData()));
			}
		});
		node.addPublisher(pub);
		node.addSubscriber(sub);
	}
	
	public void sendChatMessage(String ln) {
		Message msg = new Message();
		msg.setData(ln.getBytes());
		pub.send(msg);
	}

	public void run() {
		goOnline();
		try {
			BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
			String ln;
			while ((ln = r.readLine()) != null && !ln.equals(".")) {
				sendChatMessage(ln);
			}
		} catch (Exception x) {
			x.printStackTrace();
		}
	}

	public static void main(String[] args)  {
		System.out.println("TK3 Chat v0.1");
		TK3Chat chat = new TK3Chat();
		chat.run();
	}
}
